#!/bin/bash

SERVICE_NAME=avatar
PID_PATH_NAME=/tmp/avatar.pid
AVATAR_HOME=/home/localadmin/avatar

case $1 in
    start)
        echo "Starting $SERVICE_NAME..."
        if [ ! -f ${PID_PATH_NAME} ]; then
            cd ${AVATAR_HOME}
            mvn clean install -Dmaven.test.skip=true
            cd avatar-server
            mvn spring-boot:run &>/dev/null &
            echo $! > ${PID_PATH_NAME}
            echo "Service $SERVICE_NAME started!"
        else
            echo "Service $SERVICE_NAME is already running..."
        fi
    ;;
    stop)
        if [ -f ${PID_PATH_NAME} ]; then
            PID=$(cat ${PID_PATH_NAME});
            echo "Stopping $SERVICE_NAME..."
            kill ${PID}
            echo "Service $SERVICE_NAME stopped!"
            rm -rf ${PID_PATH_NAME}
        else
            echo "Service $SERVICE_NAME is not running!"
        fi
    ;;
    restart)
        if [ -f ${PID_PATH_NAME} ]; then
            PID=$(cat ${PID_PATH_NAME});
            echo "Stopping $SERVICE_NAME..."
            kill ${PID}
            echo "Service $SERVICE_NAME stopped!"
            rm -rf ${PID_PATH_NAME}
            echo "Starting $SERVICE_NAME..."
            cd ${AVATAR_HOME}
            mvn clean install -Dmaven.test.skip=true
            cd avatar-server
            mvn spring-boot:run &>/dev/null &
            echo $! > ${PID_PATH_NAME}
            echo "Service $SERVICE_NAME started!"
        else
            echo "Service $SERVICE_NAME is not running!"
        fi
    ;;
esac